#!/bin/env bash

# Prepended to this automatically are the following:
#SERVER=
#HOSTNAME=
#FULL_ROLES=
#REPO_URL=
#BRANCH=
#SSH_SECRET_ID=

if ! curl -fLs -m 5 -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 10" >/dev/null; then
    echo "This should be run on AWS instances, not locally."
    exit 1
fi

set -e
set -x

# Set the hostname early
echo "$HOSTNAME" >/etc/hostname
hostname "$HOSTNAME"
sed -i "s/localhost$/localhost $HOSTNAME $SERVER/" /etc/hosts

# Make sure root doesn't have a password
passwd -d root

# Allow root logins
sed -i 's/disable_root: true/disable_root: false/' /etc/cloud/cloud.cfg

# Ensure all apt updates (here and in the installer) are non-interactive
export DEBIAN_FRONTEND=noninteractive

# Dependencies to install AWS CLI
(
    apt-get -qy update
    apt-get -qy --with-new-pkgs -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" upgrade
    apt-get -qy install jq unzip curl
    apt-get -qy autoclean
)

# The following line gets subbed in with the contents of bootstrap-awscli.sh
AWS=

# Set up a bare-bones AWS configuration
mkdir -p /root/.aws
cat >/root/.aws/config <<EOF
[default]
region = us-east-1
output = text
# Credentials are from the IAM role attached to the EC2 instance
EOF

# Set up public keys for root, so we can fetch the repo; this is a
# function so we do can it again later with the zulip user
function install_keys() {
    USERNAME="$1"
    SSHDIR="$(getent passwd "$USERNAME" | cut -d: -f6)/.ssh"
    KEYDATA="$($AWS --output text \
        secretsmanager get-secret-value \
        --secret-id "$SSH_SECRET_ID" \
        --query SecretString)"
    mkdir -p "$SSHDIR"
    for KEYFILE in $(echo "$KEYDATA" | jq -r 'keys[]'); do
        echo "$KEYDATA" | jq -r ".[\"$KEYFILE\"]" | base64 -d >"$SSHDIR/$KEYFILE"
        if [[ "$KEYFILE" != *".pub" ]]; then
            chmod 600 "$SSHDIR/$KEYFILE"
        fi
    done
    chown -R "$USERNAME:$USERNAME" "$SSHDIR"
}
install_keys root

# Provide GitHub known_hosts setup; you can verify against fingerprints at
# https://docs.github.com/en/github/authenticating-to-github/githubs-ssh-key-fingerprints
# via `ssh-keygen -lf`
cat >/root/.ssh/known_hosts <<EOF
github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl
github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=
EOF

cd /root
git clone "$REPO_URL" zulip -b "$BRANCH"
git -C zulip checkout "$BRANCH"

(
    VIRTUALENV_NEEDED=$(if echo "$FULL_ROLES" | grep -q app_frontend; then echo -n yes; else echo -n no; fi)
    export VIRTUALENV_NEEDED
    export PUPPET_CLASSES="$FULL_ROLES"
    export APT_OPTIONS="-o Dpkg::Options::=--force-confnew"
    /root/zulip/scripts/setup/install \
        --self-signed-cert \
        --no-init-db
)

install_keys zulip

# Delete the ubuntu user
userdel ubuntu

reboot
